import os
import time
from logging import Logger
from typing import Callable


from starlette.requests import Request

from api.application.utils.logs import get_logger


async def log_request(request: Request, call_next: Callable):
    """
    日志中间件
    :param request:
    :param call_next:
    :return:
    """

    logger: Logger = get_logger(os.environ.get('APP_NAME'))
    start_time = time.time()
    try:
        response = await call_next(request)

    except Exception as e:
        process_time = (time.time() - start_time) * 1000
        formatted_process_time = '{0:.2f}'.format(process_time)
        logger.error(f'path={request.url.path} process_time={formatted_process_time}ms status_code=500 error={str(e)}')

    else:
        process_time = (time.time() - start_time) * 1000
        formatted_process_time = '{0:.2f}'.format(process_time)
        logger.info(f'path={request.url.path} timber={formatted_process_time}ms status_code={response.status_code}')

    return response